package com.up360.rapidcalc.aerolite
{
	
	import com.up360.rapidcalc.aerolite.consts.MyGlobal;
	import com.up360.rapidcalc.aerolite.controller.AeroliteCtrl;
	import com.up360.rapidcalc.aerolite.controller.FortCtrl;
	import com.up360.rapidcalc.aerolite.model.Aerolite;
	import com.up360.rapidcalc.aerolite.model.Configuration;
	import com.up360.rapidcalc.aerolite.model.Deploy;
	import com.up360.rapidcalc.aerolite.model.Form;
	import com.up360.rapidcalc.aerolite.model.Fort;
	import com.up360.rapidcalc.aerolite.model.Infor;
	import com.up360.rapidcalc.aerolite.model.Subject;
	import com.up360.rapidcalc.aerolite.scene.BattlefieldPage;
	import com.up360.rapidcalc.aerolite.scene.HomePage;
	import com.up360.rapidcalc.aerolite.scene.PromptPage;
	import com.up360.rapidcalc.aerolite.servers.AeroliteServer;
	import com.up360.rapidcalc.aerolite.servers.AerolitesServer;
	import com.up360.rapidcalc.aerolite.servers.ConfigurationServer;
	import com.up360.rapidcalc.aerolite.servers.DeployServer;
	import com.up360.rapidcalc.aerolite.servers.SubjectServer;
	import com.up360.rapidcalc.aerolite.servers.TopicServer;
	import com.up360.rapidcalc.aerolite.swc.AeroliteUI;
	import com.up360.rapidcalc.aerolite.swc.FortUI;
	import com.up360.rapidcalc.aerolite.swc.InforUI;
	import com.up360.rapidcalc.aerolite.swc.TopicUI;
	import com.up360.rapidcalc.aerolite.util.Exam;
	import com.up360.rapidcalc.aerolite.util.LayerManager;
	import com.up360.rapidcalc.common.util.IOHelper;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.net.URLVariables;
	import flash.utils.Timer;

	[SWF(height="600",width="876",frameRate="24")]
	public class AeroliteCrisis extends Sprite
	{
        /**
         *玩家选择错误后，暂停时间 
         */
        public static const FORBID:Number=2000;
        /**
         *用于单例 
         */
        public static var instance:AeroliteCrisis=null;
        /**
         *服务对象 
         */
        private var _topicServer:TopicServer;
        /**
         *陨石服务对象 
         */
        public var aeroliteServer:AeroliteServer;
        public var aerolitesServer:AerolitesServer;
        /**
        * 炮台
        */ 
        public var fort:Fort;
        private var _fortCtrl:FortCtrl;
        /**
         *信息条 
         */
        public var infor:Infor;
        /**
         *配置参数 
         */
        public var confi:Configuration;//配置
        public var deploy:Deploy;//游戏配置参数
        public var form:Form;//结束表单
        /**
         *题库
         */
        public var subjects:Exam;//题库
        /**
         *试题加载完成标记，加载完成为true 
         */
        public var subjectLoadComp:Boolean=false;
        /**
         *计时器 
         */
        private var _timer:Timer;
        /**
         *标记玩家是否通过游戏
         */
        public var isSuccess:Boolean=false;
        /**
         *标记玩家是否单击了 
         */
        public var isPlayerClick:Boolean=false;
        
        /**
         *层管理对象 
         */
        public var layerManager:LayerManager;
        
		public function AeroliteCrisis()
		{
			trace("陨石危机");
            addEventListener(Event.ADDED_TO_STAGE,function(e:Event):void
            {
                MyGlobal.stage=stage;
            });
            layerManager=new LayerManager(this);
            //
            aeroliteServer=new AeroliteServer();
            aerolitesServer=new AerolitesServer();
            _topicServer=new TopicServer(new TopicUI());
            setupTimer();
            //用于没有外框清楚下的本地测试
            if(this.parent is Stage){
                var b_vals:Object=new Object();
                b_vals.type="1";
                b_vals.userId="123456";
                b_vals.contCpId="2";
                b_vals.config='{"hitTime":10,"aeroCount":50}';
                b_vals.subjectDataURL="getQuestion.txt";
                b_vals.getTop="getTop.txt";
                b_vals.saveResultURL="getQuestion.txt";
                playGame(b_vals);
            }
            //
			addEventListener("aeroliteBlowUp",aeroliteBlowUp);
		}
        /**
         * 陨石爆后响应 
         * @param event
         */
        private function aeroliteBlowUp(event:Event):void
        {
//            trace("aerolite blow up");
            //取得陨石对象，将其从显示列表中删除，并从陨石列表中删除
            var b_target:Aerolite=(event.target as MovieClip).parent as Aerolite;
            layerManager.remove(b_target);
            //判断陨石是到达炮台自爆，还是由于玩家选择正确爆了
            if(!isPlayerClick)
            {
                return;
            }
            isPlayerClick=false;
        }
        
        /**
         *炮台被灭了 
         */
        public function fortBeKill():void
        {
            isSuccess=false;
            stop();
            fort.addEventListener("fortBlowup",fortBlowup);
            fort.updateGunPlatform(Fort.BLOWUP);
        }
        
        private function fortBlowup(event:Event):void
        {
            fort.visible=false;
            gameover();
        }
        /**
         *添加一块新陨石 
         * 
         */
        private function addAerolite():void
        {
            if(subjects.size()>0)
            {
                aerolitesServer.add(newAerolite());
            }
        }
        
        private function nextStep():void
        {
            //更新infor
            infor.breakUp();
            //添加一块新的陨石
            addAerolite();
            //
            if(aerolitesServer.size()>0)
            {
                _topicServer.update(aerolitesServer.curTopic());
            }
            else
            {
                _topicServer.update("");
                isSuccess=true;
                gameover();
            }
        }
        /**
         *生成一块陨石 
         * @return 
         * 
         */
        public function newAerolite():Aerolite
        {
            //取得从题库中取得一道题目
            var b_subject:Subject=subjects.randomGet();
            if(b_subject==null) return null;
			//陨石对象
            var b_aerolite:Aerolite=new Aerolite();
            //设置皮肤
            b_aerolite.ui=new AeroliteUI();
            //设置答案
            b_aerolite.answer=b_subject;
            //设置撞击时间
            b_aerolite.hitTime=deploy.hitTime*1000;
            //设置终点
            b_aerolite.finish=new Point(fort.x,fort.y);
            //设置位置
            aeroliteServer.aerolite=b_aerolite;
            aeroliteServer.randomOutset();
            //更新皮肤颜色
            aeroliteServer.randomColor();
			//生成一个控制对象
			var b_ctrl:AeroliteCtrl=new AeroliteCtrl();
			b_aerolite.ctrl=b_ctrl;
            //
            layerManager.add(b_aerolite,LayerManager.GAME);
            return b_aerolite;
        }
        
        /**
         *开始游戏  
         */
        public function start():void
        {
            //判断题目是否已经加载完毕
            if(!subjectLoadComp)
            {
                trace("subject loading! please wait!");
                return;
            }
            //清空
            clearUI();
            //加入UI
            addStartUI();
        }
        
        /**
         *重新开始 
         */
        public function restart():void
        {
            //初始化数据
            initData();
            //加载题目
            loadSubject();
        }
        
        /**
         *停止 
         */
        public function stop():void
        {
           aerolitesServer.stop();
           infor.stop();
           _fortCtrl.clear();
        }
        /**
         * 游戏结束
         */
        public function gameover():void
        {
            //当游戏已经结束，则不进行下面操作。
            if(form.successFlag>=0) return;
            //
            stop();
            //
            form.successFlag=isSuccess?1:0;
            form.rightCount=infor.breakup;
            form.consTime=infor.userTime;
            //
            switch(confi.type)
            {
                case Configuration.OFFICAL:
                    //往服务器发送保存游戏结果请求,等待请求结束
                    saveResult();
                    break;
                case Configuration.PREVIEW:
                    showPromptPage();
                    break;
                case Configuration.SCENARIO_CLASSROOM:
                    showPromptPage();
                    break;
                default:
                    trace("配置数据的类型出错!");
                    break;
            }
            
        }
        
        /**
         *显示提示页面,即成功或失败结束框 
         */
        public function showPromptPage():void
        {
            var b_promptPage:PromptPage=new PromptPage(form,isSuccess);
            b_promptPage.x=123;
            b_promptPage.y=27;
            
            var b_urlVals:URLVariables=new URLVariables();
            b_urlVals.contCpId=confi.contCpId;
            b_promptPage.updateRanking(confi.getTop,b_urlVals);
            layerManager.add(b_promptPage,LayerManager.OUTLOOK);
        }
        /**
         * 判断指定陨石与当前题干所对应的答案是否一致,若相等，则返回true
         * @param aero
         * @return 
         */
        public function judge(aero:Aerolite):Boolean
        {
            var b_result:Boolean=false;
            var b_answer:String=aerolitesServer.curAnswer();
            var b_userAnswer:String=aero.answer.rightAnswer();
            b_result=b_answer==b_userAnswer;
            if(b_result)
            {
                //
                fort.fire(aero);
                //
                aerolitesServer.remove(aero);
                //
                nextStep();
            }
            else
            {
                //加入错误题库
                form.errorSubject.addNoRepeat(aerolitesServer.curSubject());
                form.wrongCount++;
                //禁止炮台
                timerStart();
            }
            return b_result;
        }
        
        public function playGame(vals:Object):void
        {
            instance=this;
            //
            var b_confiServer:ConfigurationServer=new ConfigurationServer();
            confi=b_confiServer.getConfi(vals);
            //
            var b_deployServer:DeployServer=new DeployServer();
            deploy=b_deployServer.getDeploy(JSON.parse(confi.config));
            //加载题库
            loadSubject();
            //初始化form对象
            initForm();
            //显示首页
            homePage();
        }
        
        /**
         *加载试题 
         */
        public function loadSubject():void
        {
            subjectLoadComp=false;
            var b_urlVals:URLVariables=new URLVariables();
            b_urlVals.contCpId=confi.contCpId;
            b_urlVals.sCount=deploy.aeroCount;
            IOHelper.request(confi.subjectDataURL,b_urlVals,subjectComp,subjectError);
        }
        
        public function saveResult():void
        {
            var b_urlVals:URLVariables=new URLVariables();
            b_urlVals.userId=confi.userId;
            b_urlVals.contCpId=confi.contCpId;
            b_urlVals.rightCount=form.rightCount;
            b_urlVals.quesCount=form.rightCount;
            b_urlVals.consTime=form.consTime;
            b_urlVals.successFlag=form.successFlag;
            IOHelper.request(confi.saveResultURL,b_urlVals,saveResultComp,saveResultError);
        }
        
        /**
         *问题列表数据加载成功 
         */
        private function subjectComp(data:Object):void
        {
//            trace("subject request finished!");
            checkSubjects();
            var b_subjectServer:SubjectServer=new SubjectServer();
            var b_subjectArr:Array=b_subjectServer.getSubjects(data.subject as Array);
            for each(var sub:Object in b_subjectArr)
            {
                subjects.add(sub);
            }
//            subjects.display();
            subjectLoadComp=true;
        }
        /**
         *检测一下题库 
         */
        private function checkSubjects():void
        {
            if(subjects)
            {
                subjects.clear();
            }
            else
            {
                subjects=new Exam();
            }
                
        }
        /**
         *首页 
         */
        private function homePage():void
        {
            var b_homePage:HomePage=new HomePage();
            layerManager.add(b_homePage);
        }
        /**
         *问题列表数据加载失败 
         * 
         */
        private function subjectError():void
        {
            trace("subject request fail!");
        }
        
        /**
         * 保存结果失败
         * 
         */
        private function saveResultError():void
        {
            trace("save result request fail!");
        }
        
        /**
         * 保存结果成功
         */
        private function saveResultComp(data:Object):void
        {
            trace("save result comp!");
            showPromptPage();
        }
        /**
         *配置计时器 
         */
        private function setupTimer():void
        {
            _timer=new Timer(FORBID);
            _timer.addEventListener(TimerEvent.TIMER,timerTimer);
        }
        
        private function timerStart():void
        {
            if(_timer.delay==FORBID){
                fort.updateGunPlatform(Fort.STOP);
                _fortCtrl.parseCtrl();
                MyGlobal.stage.mouseChildren=false;
            }
            _timer.start();
        }
        
        private function timerTimer(event:Event):void
        {
            if(_timer.delay==FORBID)
            {
                fort.updateGunPlatform(Fort.NORMAL);
                _fortCtrl.control();
                MyGlobal.stage.mouseChildren=true;
                _timer.stop();
            }
            else
            {
                if(aerolitesServer.size()>=AerolitesServer.MAX_LENGTH||subjects.isEmpty())
                {
                    _timer.delay=FORBID;
                    _timer.stop();
                    //
                    _topicServer.update(aerolitesServer.curTopic());
                }
                else
                {
                    addAerolite();
                }
            }
        }
        
        /**
         *初始化清空 
         */
        private function initData():void
        {
            form.clear();
            fort.clear();
            aeroliteServer.clear();
            aerolitesServer.clear();
            checkSubjects();
            subjectLoadComp=false;
            isSuccess=false;
            isPlayerClick=false;
        }
        
        /**
         *初始化表单 
         */
        private function initForm():void
        {
            //生成表单
            form=new Form();
            form.contCpId=confi.contCpId;
            form.userId=confi.userId;
            form.wrongCount=0;
        }
        
        private function clearUI():void
        {
            layerManager.clear();
        }
        /**
         *添加游戏开始界面 
         */
        private function addStartUI():void
        {
            //加入战场
            var b_battleField:BattlefieldPage=new BattlefieldPage();
            layerManager.add(b_battleField);
            //加入题干显示块
            _topicServer.show(412,410);
            _topicServer.update("");
            //加入信息条
            infor=new Infor();
            infor.level=confi.contCpId;
            infor.surplus=subjects.size();
            infor.breakup=0;
            infor.ui=new InforUI();
            infor.x=436.75;
            infor.y=61.2;
            infor.mouseChildren=false;
            infor.mouseEnabled=false;
            layerManager.add(infor,LayerManager.OUTLOOK);
            //加入炮台
            fort=new Fort(new FortUI());
            fort.x=434;
            fort.y=524;
            _fortCtrl=new FortCtrl();
            fort.ctrl=_fortCtrl;
            layerManager.add(fort,LayerManager.GAME);
            //
            initAddAerolite();
            //
            infor.start();
        }
        
        private function initAddAerolite():void
        {
            _timer.delay=40;
            //
            aerolitesServer.start();
            timerStart();
        }
    }
}